package com.agentframework.core.environment;

import com.agentframework.core.agent.Agent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 环境完成检查器，统一管理环境结束条件
 */
public class EnvironmentCompletionChecker {
    private static final Logger logger = LoggerFactory.getLogger(EnvironmentCompletionChecker.class);
    private final AbstractEnvironment environment;
    private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor(r -> {
        Thread t = new Thread(r);
        t.setName("EnvCompletionChecker");
        return t;
    });
    
    // 记录上次检查时的消息数量
    private int lastMessageCount = 0;
    // 连续检查到消息数量相同的次数
    private int stableCount = 0;
    
    public EnvironmentCompletionChecker(AbstractEnvironment environment) {
        this.environment = environment;
    }

    public void startChecking() {
        logger.debug("Starting environment completion checker for env {}", environment.getEnvId());
        // 延迟30秒开始检查，每5秒检查一次
        scheduler.scheduleAtFixedRate(this::checkCompletion, 30, 5, TimeUnit.SECONDS);
    }

    /**
     * 检查环境是否可以结束
     * 通过多个维度的检查确保环境安全结束：
     * 1. 消息处理完整性：确保所有消息都被处理
     * 2. 任务状态准确性：确保所有异步任务都完成
     * 3. 环境状态稳定性：确保状态持续稳定一段时间
     * 4. 异常情况处理：处理各种边界情况
     */
    private void checkCompletion() {
        List<Agent> agents = environment.getAgents();
        if (agents.isEmpty()) {
            logger.warn("No agents in environment {}, cannot check completion", environment.getEnvId());
            return;
        }

        // 1. 检查自定义结束条件
        boolean anyConditionMet = environment.getEndConditions().stream()
                .anyMatch(c -> {
                    try {
                        return c.shouldEnd(environment);
                    } catch (Exception e) {
                        logger.error("Error checking end condition", e);
                        return false;
                    }
                });

        // 2. 检查所有agent的状态
        boolean allIdle = agents.stream().allMatch(agent -> {
            try {
                // 2.2 检查消息队列是否为空
                boolean hasNoMessages = agent.getContext().popAllMessage().isEmpty();

                // 2.3 检查是否有未处理的历史消息
                boolean hasNoHistoryMessages = agent.getContext().getNews().isEmpty();

                // 2.4 检查是否有未完成的动作
                boolean hasNoPendingActions = agent.getContext().getTodo() == null;

                return hasNoMessages && hasNoHistoryMessages && hasNoPendingActions;
            } catch (Exception e) {
                logger.error("Error checking agent {} status", agent.getAgentId(), e);
                return false;
            }
        });

        // 4. 检查消息数量稳定性
        int currentMessageCount = agents.stream()
                .mapToInt(agent -> {
                    try {
                        return agent.getContext().getMessageSize();
                    } catch (Exception e) {
                        logger.error("Error getting message size for agent {}", agent.getAgentId(), e);
                        return 0;
                    }
                })
                .sum();

        // 5. 更新消息稳定性计数
        if (currentMessageCount == lastMessageCount) {
            stableCount++;
        } else {
            stableCount = 0;
            lastMessageCount = currentMessageCount;
        }

        // 6. 检查环境状态
        boolean isEnvironmentStable = stableCount >= 3;
        boolean canComplete = (anyConditionMet || (allIdle && isEnvironmentStable));

        // 7. 记录详细的状态信息
        if (canComplete) {
            logger.info("Environment completion conditions met for environment {}", environment.getEnvId());
            logger.debug("Completion details: " +
                            "anyConditionMet={}, " +
                            "allIdle={}, " +
                            "isEnvironmentStable={}, " +
                            "messageCount={}, " +
                            "stableCount={}, " +
                            "agentCount={}",
                    anyConditionMet,
                    allIdle,
                    isEnvironmentStable,
                    currentMessageCount,
                    stableCount,
                    agents.size()
            );

            // 8. 安全关闭环境
            try {
                environment.completeEnvironment();
                scheduler.shutdown();
            } catch (Exception e) {
                logger.error("Error completing environment {}", environment.getEnvId(), e);
            }
        } else {
            // 9. 记录未完成原因
            logger.debug("Environment not ready for completion: " +
                            "anyConditionMet={}, " +
                            "isShutdownRequested={}, " +
                            "allIdle={}, " +
                            "isEnvironmentStable={}, " +
                            "messageCount={}, " +
                            "stableCount={}",
                    false,
                    false,
                    allIdle,
                    isEnvironmentStable,
                    currentMessageCount,
                    stableCount
            );
        }
    }
} 